<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import AddCoordinate from "@/components/AddCoordinate/index.vue";
import { useMapStoreHook } from "@/store/modules/map";
import { GetAllStation } from '@/utils/api/dispatch/station'
import { PureTableBar } from "@/components/RePureTableBar";
import { useDept } from "./utils/crossHook";
import { getCross, updateCross, addCross } from '@/utils/api/dispatch/cross'
import { cloneDeep} from "lodash";
import Konva from "konva";

const pureMap = useMapStoreHook()

interface Props {
  formInline:{
    name?: string,
    status?: number,
    stationList?: any,
    note?: string,
    type?: number,
    stationids?: any
  }
}

const props = withDefaults(defineProps<Props>(), {
  formInline: () => ({
    name: "",
    status: 1,
    stationList: [],
    note: "",
    type: 1,
    stationids: []
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);
const stationOptions = ref([]);
var isUpdate = ref(false)
const {
  columns,
  loading,
  dataList,
  onSearch,
  pagination,
} = useDept();

function getRef() {
  return ruleFormRef.value;
}

watch(newFormInline,(newValue,oldValue)=>{
  
},{deep:true})

// pureMap.$subscribe((mutation, state) => {
//   console.log( mutation, state )
// }, {
//   detached: true
// })

function crossNameChange(val){
  pureMap.$patch((state)=>{
    state.crossDetail.name = val
  })
}

function chores(title,data) {
  message(`${title}成功`, {
    type: "success"
  });
  pureMap.targetCross.name(`cross-${pureMap.crossDetail.name}`)
  pureMap.targetCross.attrs.type = 1
  onSearch()
  pureMap.$patch({
    crossSwitch: false
  })
  isUpdate.value = false
  resetForm(ruleFormRef.value)
}

/**
 * 新增或修改时都需要给地图上所选中的交管数据添加一个交管状态
 * 新增：1
*/
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      var data = newFormInline.value
      data.stationids = newFormInline.value?.stationids?.toString()
      if(isUpdate.value){
        updateCross(data).then(res => {
          if (res.Code === 0) chores('修改',data)
          pureMap.targetCross.children.forEach(v=>{
            if(v.name() === 'circle'){
              v.fill('red')
            }else{
              v.stroke('red')
            }
          })
        })
      }else{
        addCross(data).then(res=>{
          if (res.Code === 0){
            chores('新增',data)
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
   if (!formEl) return
  formEl.resetFields()
  connect()
  isUpdate.value = false
  if(pureMap.targetCross.attrs.type !== 1){
    pureMap.targetCross.destroy()
  }

  pureMap.targetCross.children.forEach(v=>{
    if(v.name() === 'circle'){
      v.fill('red')
    }else{
      v.stroke('red')
    }
  })
}

// 编辑
async function crossUpdate(id: number) {
  let { Content } = await getCross(id)
  newFormInline.value = Content
  newFormInline.value.stationids = newFormInline.value?.stationids?.split(',').map(v=>{return Number(v)})
  for(let key in pureMap.crossDetail){
    pureMap.$patch((state)=>{
      state.crossDetail[key] = Content[key]
    })
  }
  isUpdate.value = true

  pureMap.getCross(pureMap.stageKonva.find(`.cross-${pureMap.crossDetail.name}`)[0])
}

// 关联form与pureMap
function connect(){
  Object.keys(pureMap.crossDetail).forEach(v=>{
    pureMap.$patch((state)=>{
      state.crossDetail[v] = newFormInline.value[v]
    })
  })
}

onMounted(async ()=>{
  // 站点下拉
  const { Content } = await GetAllStation()
  stationOptions.value = Content

  connect()
})


defineExpose({ getRef });
</script>

<template>
  <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="50px">
    <el-row :gutter="30">
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="名称" prop="name">
          <el-input v-model="newFormInline.name" size="small" clearable placeholder="请输入名称" @change="crossNameChange" />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="类型" prop="type">
          <el-select v-model="newFormInline.type" size="small" placeholder="请选择交管类型" style="width:100%">
            <!-- <el-option label="站点交管" :value="0" /> -->
            <el-option label="唯一区域交管" :value="1" />
            <el-option label="巷道区域交管" :value="2" />
            <el-option label="公共区域交管" :value="3" />
          </el-select>
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="状态" prop="status">
          <el-select v-model="newFormInline.status" size="small" placeholder="请选择状态" style="width:100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="锁定" :value="2" />
          </el-select>
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24" v-show="!newFormInline.type">
        <el-form-item label="站点集合" prop="stationids" label-width="70px">
          <el-select v-model="newFormInline.stationids" size="small" multiple placeholder="请选择站点集合" style="width:100%">
            <el-option v-for="item in stationOptions" :key="item.stationid" :label="item.stationname" :value="item.stationid" />
          </el-select>
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24" v-show="newFormInline.type">
        <el-form-item label="区域" prop="stationList" style="font-weight: 700;">
          <Add-coordinate :data="newFormInline.stationList"></Add-coordinate>
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="备注" prop="note">
          <el-input v-model="newFormInline.note" size="small" clearable placeholder="请输入备注" type="textarea" />
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          <el-button type="danger" @click="resetForm(ruleFormRef)">清空数据</el-button>
        </el-form-item>
      </re-col>
    </el-row>
  </el-form>

  <PureTableBar title="交管列表" :columns="columns" size="small" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <pure-table ref="tableRef" adaptive align-whole="center" row-key="Id" showOverflowTooltip table-layout="auto"
          :loading="loading" :size="size" :data="dataList" :columns="dynamicColumns" :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false" :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }">
          <template #operation="{ row }">
            <el-button class="reset-margin" :size="size" link type="primary" @click="crossUpdate(row.id)">
              编辑
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
</template>

<style lang="scss" scoped>
.el-radio {
  margin-right: 16px;
}
</style>
